import sys
import csv
from optparse import make_option

from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand

from satchmo_tuning.models import CategoryTuning

class UploadCommand(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--encoding', action='store', dest='encoding',
            type='string', default='cp1251',
            help='CSV file encoding'),
    )
    args = 'filename'

    def handle(self, filename=None, **options):

        if not filename:
            sys.stderr.write(self.style.ERROR("CSV file is not specified.\n"))
            return

        try:
            file = open(filename, 'r')
        except IOError, e:
            sys.stderr.write(self.style.ERROR("Can't open CSV file. %s\n" % e))
            return

        self.cached_categories = {}
        self.options = options

        reader = csv.reader(file, delimiter=';')
        site = Site.objects.get_current()
        encoding = options.get('encoding')

        self.handle_reader(reader, site, encoding)

    def get_category(self, code):
        category = self.cached_categories.get(code)
        if not category:
            try:
                category = CategoryTuning.objects.get(code=code)
                self.cached_categories[code] = category
            except CategoryTuning.DoesNotExist:
                pass            
        return category

    def handle_reader(self, reader, site, encoding):
        raise NotImplementedError
